﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace THFDownloader
{
    public partial class frmBootStrap : Form
    {
        private string[] args;
        private bool update;
        private string tempFolderName;

        public frmBootStrap(string[] mArgs)
        {
            InitializeComponent();
            args = mArgs;
        }

        public static int CompareVersions(String strA, String strB)
        {
            Version vA = new Version(strA.Replace(",", "."));
            Version vB = new Version(strB.Replace(",", "."));

            return vA.CompareTo(vB);
        }

        private void frmBootStrap_Load(object sender, EventArgs e)
        {
            string versionChecked = "";
            string versionCurrent = Assembly.GetEntryAssembly().GetName().Version.ToString();
            string tempFolderName = System.IO.Path.GetRandomFileName();
            //bool updateRequired = false;

            if (args.Length == 0)
            {
                // Placeholder for Greg when he's working offline.
                //var versionURL = "http://127.0.0.1/THFMAIN/version.cfg;"
                var versionURL = "http://s3.amazonaws.com/THFMAIN/version.cfg";

                WebClient client = new WebClient();

                using (var stream = client.OpenRead(versionURL))
                using (var reader = new StreamReader(stream))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        string[] lineName = line.Split(new Char[] { '=' });
                        versionChecked = Convert.ToString(lineName[1]);
                    }
                }
                //if (CompareVersions(versionChecked, versionCurrent) > 0) { updateRequired = true; }
                if (CompareVersions(versionChecked, versionCurrent) > 0) { update = true; }
            }

            if (args.Length > 0) { update = true; }

            if (!update)
            {
                this.Close();
            }
            else
            {
                this.Tag = tempFolderName;
                timer1.Start();
            }
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            if (args.Length == 0)
            {
                // Placeholder for Greg when he's working offline.
                //var downloadURL = "http://127.0.0.1/THFMAIN/DOWNLOADER/THFDownloader.exe";
                //var downloadURL = "http://s3.amazonaws.com/THFMAIN/DOWNLOADER/THFDownloader.exe";
                System.Uri downloadURL = new System.Uri("http://s3.amazonaws.com/THFMAIN/DOWNLOADER/THFDownloader.exe");
                tempFolderName = Convert.ToString(this.Tag);

                if (!Directory.Exists(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + tempFolderName))
                {
                    Directory.CreateDirectory(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + tempFolderName);
                }

                try
                {
                    WebClient Client = new WebClient();
                    Client.DownloadFile(downloadURL, System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + tempFolderName + "\\" + "THFDownloader.exe");
                }
                catch
                {
                    MessageBox.Show("ERROR: Please check your internet connection.");
                }
                if (File.Exists(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + "THFDownloader.exe"))
                {
                    System.Diagnostics.Process.Start(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + tempFolderName + "\\" + "THFDownloader.exe", tempFolderName + " 1");
                    //Application.Exit();
                }
                update = false;
                timer1.Enabled = false;
            }
            else
            {
                // LOAD PATCHER FORM
            }

            if (args.Length != 0)
            {
                if (Convert.ToInt32(args[1]) == 1)
                {
                    Process[] procs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension("THFDownloader.exe"));

                    foreach (Process proc in procs)
                    {
                        if (proc.Id != Convert.ToInt32(Process.GetCurrentProcess().Id))
                        {
                            proc.Kill();
                        }
                    }

                    System.Threading.Thread.Sleep(200);

                    if (File.Exists(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), @"..") + "\\" + "THFDownloader.exe"))
                    {
                        try
                        {
                            File.SetAttributes(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), @"..") + "\\" + "THFDownloader.exe", FileAttributes.Normal);
                            File.Delete(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), @"..") + "\\" + "THFDownloader.exe");
                        }
                        catch
                        {
                            MessageBox.Show("ERROR (1): Access Denied - Cannot delete file.");
                        }
                    }

                    File.Copy(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + "THFDownloader.exe", System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), @"..") + "\\" + "THFDownloader.exe",true);
                    File.SetAttributes(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), @"..") + "\\" + "THFDownloader.exe", FileAttributes.Normal);

                    System.Threading.Thread.Sleep(300);
                    
                    if (File.Exists(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), @"..") + "\\" + "THFDownloader.exe"))
                    {
                        //Console.WriteLine(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), @"..") + "\\" + "THFDownloader.exe " + Convert.ToString(args[0]) + " 2");
                        timer1.Enabled = false;
                        args[1] = "5";
                        System.Diagnostics.Process.Start(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), @"..") + "\\" + "THFDownloader.exe ", Convert.ToString(args[0]) + " 2");
                        //Application.Exit();
                    }

                }

                if (Convert.ToInt32(args[1]) == 2)
                {
                    Process[] procs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension("THFDownloader.exe"));

                    foreach (Process proc in procs)
                    {
                        if (proc.Id != Convert.ToInt32(Process.GetCurrentProcess().Id))
                        {
                            proc.Kill();
                        }
                    }

                    System.Threading.Thread.Sleep(200);

                    if (File.Exists(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + Convert.ToString(args[0]) + "\\" + "THFDownloader.exe"))
                    {
                        try
                        {
                            File.Delete(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + Convert.ToString(args[0]) + "\\" + "THFDownloader.exe");
                        }
                        catch
                        {
                            MessageBox.Show("ERROR (2): Access Denied - Cannot delete file.");
                        }
                    }
                    if (Directory.Exists(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + Convert.ToString(args[0])))
                    {
                        try
                        {
                            Directory.Delete(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + Convert.ToString(args[0]));
                        }
                        catch
                        {
                            MessageBox.Show("ERROR (2): Access Denied - Cannot delete folder.");
                        }
                    }
                    update = false;
                    timer1.Enabled = false;
                    this.Close();
                }
            }
        }
    }
}
